package com.ayf.payment.game.api.service.platform.impl;

import com.ayf.payment.game.api.dto.platform.TokenAdmin;
import com.ayf.payment.game.api.entity.platform.AdminUser;
import com.ayf.payment.game.api.service.platform.AdminLogService;
import com.ayf.payment.game.api.service.platform.AdminUserService;
import com.ayf.payment.game.api.service.platform.TokenAdminRepository;
import com.ayf.payment.game.api.service.platform.TokenAdminService;
import com.ayf.payment.game.api.utils.TokenUtils;
import com.swwx.charm.commons.lang.exception.SystemErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 *
 * @author wwl
 * @date 2020/3/4 12:03
 */
@Service
public class TokenAdminServiceImpl implements TokenAdminService {

    @Autowired
    private TokenAdminRepository tokenAdminRepository;

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private AdminLogService adminLogService;

    @Override
    public TokenAdmin createToken(Integer adminUserId,String Ip) {
        TokenAdmin entity =new TokenAdmin();
        entity.setAdminUserId(adminUserId);
        entity.setIp(Ip);
        entity.setExpiredSeconds(TokenAdminRepository.ACCESS_TOKEN_ADMIN_EXPIRED_SECOND);
        String accessToken = TokenUtils.genAccessToken();
        entity.setAccessToken(accessToken);
        entity.setRefreshToken(TokenUtils.genRefreshToken(accessToken));
        if (tokenAdminRepository.save(entity)){
            return entity;
        }
        return null;
    }

    @Override
    public void deleteToken(Integer adminUserId,String IP) {
        AdminUser temp=new AdminUser();
        temp.setId(adminUserId);
        AdminUser adminUser = adminUserService.selectOne(temp);
        if (adminUser == null) {
            throw new SystemErrorException("adminUserId is not found.");
        }
        tokenAdminRepository.delete(adminUserId);
    }
}
